package com.nuodui.service.impl;

import com.nuodui.domain.po.QuestTopic;
import com.nuodui.domain.vo.GetAnalysisDataByTopicIdVO;
import com.nuodui.domain.vo.GetAnalysisListDataByTopicIdVO;
import com.nuodui.mapper.QuestAnswerOptionsMapper;
import com.nuodui.mapper.QuestTopicMapper;
import com.nuodui.service.IAnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.List;

@Service
public class AnalysisServiceImpl implements IAnalysisService {

    @Autowired
    private QuestTopicMapper questTopicMapper;
    @Autowired
    private QuestAnswerOptionsMapper questAnswerOptionsMapper;

    @Override
    public GetAnalysisDataByTopicIdVO getAnalysisDataByTopicId(String topicId) {

        GetAnalysisDataByTopicIdVO vo = new GetAnalysisDataByTopicIdVO();

        //1、topic名字
        QuestTopic questTopic = questTopicMapper.selectById(topicId);
        if(questTopic == null){
            throw new IllegalArgumentException("问题不存在!");
        }

        vo.setContent(questTopic.getTopicTitle());

        //2.获取list
        List<GetAnalysisListDataByTopicIdVO> list =
                questAnswerOptionsMapper.getAnswerCountDataByTopicId(topicId);

        vo.setList(list);

        //3.统计count
        vo.setCount(list.stream().mapToInt(GetAnalysisListDataByTopicIdVO::getCount).sum());

        //4.处理占比
        list.forEach(item -> {
            //获取到每一个数据 count / 总count 保留两位有效数字，增加百分号
            String ratio = calculatePercentage(item.getCount(), vo.getCount());
            item.setRatio(ratio);
        });

        return vo;
    }

    /**
     * 计算并格式化百分比，保留两位有效数字，并添加百分号。
     *
     * @param part 部分数值
     * @param whole 总数值
     * @return 格式化后的百分比字符串
     */
    public static String calculatePercentage(int part, int whole) {
        double percentage = ((double) part / whole) * 100; // 计算百分比 0.1256 -> 12.56
        DecimalFormat df = new DecimalFormat("#.##"); // 创建格式化对象，保留两位有效数字
        return df.format(percentage) + "%"; // 格式化并添加百分号
    }

}
